<?// Определяем корневой путь
if(isset($_SERVER['HTTP_HOST'])){ // локалка/denwer
  if ($_SERVER['HTTP_HOST'] == 'neftemagnat.ru' && $_SERVER['SERVER_ADDR'] == '127.0.0.1')
    $DOCUMENT_ROOT = $_SERVER["DOCUMENT_ROOT"]; // Этот путь будет использоваться при работе с localhost
   elseif (($_SERVER['HTTP_HOST'] == 'neftemagnat.ru' || $_SERVER['HTTP_HOST'] == 'www.neftemagnat.ru') && $_SERVER['SERVER_ADDR'] != '127.0.0.1')
   	$DOCUMENT_ROOT = '/home/www/neftemagnat.ru/www';
  else $DOCUMENT_ROOT = '/home/neftemagnat.ru/www';
}
else
  $DOCUMENT_ROOT = ''; // Этот путь будет использоваться при работе отладчика Зенда (для корректной работы нужно внести правки в конфигурационный файл для ABSPATH)
$script = TRUE;
require_once($DOCUMENT_ROOT . '/../neftemagnat_start.php'); // Подключаем файл инициализации
// в файле инициализации обновляем время последнего посещения юзера, делаем доступным объект objUser
// и проверку на залогиненность $objUser->isLoggedIn() return true | false;
//--
setlocale(LC_ALL, 'ru_RU'); //установка русской локали

if ($objUser->isLoggedIn())
    $idUser= $objUser->getIdUser(); // изменить дописать 
else
    $idUser = NULL;
$path=""; //корень

$typeOfQuery = NULL;

if (isset($_POST["dataSend"])){ //проверяем было ли что-нибудь прислано от клиента через JS
    $dataFromClient = $_POST["dataSend"]; 
    $typeOfQuery = $dataFromClient["query"]; 
}



switch ($typeOfQuery) {

    case "initial":
        
        //получение данных от клиента
        $option = $dataFromClient['option'];
        
        //обезопашивание объекта $option
        foreach ($option as $key => $value) {
            $key = absolutelyEscapeString($key);
            $value = absolutelyEscapeString($value);
            $option_[$key] = $value;
        }
        unset($option);
        $option = $option_;
        unset($option_);
        //*********конец получения-обезопасивания данных
        
        /* проверка данных на корректность
        *
         * $option - должен быть объектом, содержащий option['essense'] . возможные значение "firm", "office", "build",
         * option['idEssence'] - айдишник сущности
         * 
         */
        
        $error = NULL;
        $ess = array('firm', 'office', 'build');
        
        if (!$error && !isset($option['essence'])) 
            $error = 'Неизвестна ошибка_1';
            
        if (!$error && !in_array($option['essence'], $ess) )
            $error = 'Неизвестна ошибка_2';
        
        if (!$error && !isset($option['idEssence']) )
            $error = 'Неизвестна ошибка_3';
        
        if (!$error && !filter_var($option['idEssence'], FILTER_VALIDATE_INT) )
            $error = 'Неизвестная ошибка_4';
        
        //********* конец проверки на корректность
        
        if (!$error){
            
            $query = "SELECT city.name AS cityName, firms.id_firm AS id_firm, firms.description AS description, firms.name AS name, building.lat AS lat, building.lng AS lng
                      FROM firms
                      LEFT JOIN building_offices USING (id_office)
                      LEFT JOIN building USING (id_building)
                      LEFT JOIN city ON (city.city_id = building.id_city)
                      WHERE firms.id_firm = '".$option['idEssence']."'
                      ";
            $query_ = mysql_query($query);
            
            if (mysql_num_rows($query_) != 1) 
                $error = 'Неизвестная ошибка_5';  
        }
        
        //если нету ошибки
        if (!$error){
            
            $result = mysql_fetch_array($query_);
            
            $answer['lat'] = $result['lat'];
            $answer['lng'] = $result['lng'];
            $answer['idFirm'] = $result['id_firm'];
            $answer['name'] = $result['name'];
            $answer['description'] = $result['description'];
            $city = $result['cityName'];
            $answer['cityName'] = $city;
            
            $HTMLessence = '
                <table>
                    <tr>
                        <td rowspan="1" width="75px"><img src="'.W_IMAGES.'firms_50/none.jpg"></td>
                        <td><span style="font-size: 15px; font-weight: bold">'.$result['name'].'</span><br>
                            <span style="font-size: 10px; font-weight: bold; color: grey;">'.$result['description'].'</span></td>
                    </tr>
                    <tr>
                        <td>
                        <a style="color: blue" href="#">смотреть фирму</a>
                        </td>
                        <td>
                        <a style="color: blue" href="#">смотреть здание</a>
                        </td>
                    </tr>
                </table>';
            
            
            $answer['HTMLessence'] = $HTMLessence;

            $answer['error'] = addslashes($error);
        
            $messageInitial = '<div class="map_canvas" id="map_canvas" style="margin: 0px auto; padding: 20px"></div>';
          
            //!!!!!begin FILTR          $messageInitial  .= '<div id="filtr">';
               
             ob_start();
                include BLOCKS.'_map/yourCity.php';
                $messageInitial  .= ob_get_contents();    
             ob_end_clean();
//            
             $messageInitial .= ' 
                 <br>
                 <br>
                <a href="#" style="font-size:15px; color: #1e90ff; font-weight: bold" onClick="_map.changeFirm(); return false;">выбрать другую фирму</a>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                <a href="#" style="font-size:15px; color: #1e90ff; font-weight: bold">оставить прежнюю фирму</a>                  </div> <!-- end of filtr-->';
        
              $answer['messageInitial'] = $messageInitial;
              $answer['aim'] = 2;
        } //end of if(!$error)
        
        $objJSON = new Service_JSON(); // иницилизация объета JSON

        echo $objJSON->encode($answer);
        
    break;
    
    case "getFiltr":
        
        $error = NULL;
        
        $storage = $dataFromClient['storage'];
        
        $latAround = absolutelyEscapeString($storage['map']['centerLat']);
        $lngAround = absolutelyEscapeString($storage['map']['centerLng']);
        $zoom = absolutelyEscapeString($storage['map']['zoom']);
        $city = absolutelyEscapeString($storage['ourGeo']['ourCity']);
        $aim = absolutelyEscapeString($storage['search']['aim']);
        $searchWord = absolutelyEscapeString($storage['search']['searchWord']);
        $freeOffice = absolutelyEscapeString($storage['search']['freeOffice']);
        $freeVacancy = absolutelyEscapeString($storage['search']['freeVacancy']);
        $showSpecForm = absolutelyEscapeString($storage['search']['showSpecForm']);
        $salaryFrom =  absolutelyEscapeString( $storage['search']['salaryFrom'] );
        $experienceFrom =  absolutelyEscapeString( $storage['search']['experienceFrom'] );
        $ageFrom =  absolutelyEscapeString( $storage['search']['ageFrom'] );
        $ageUnder =  absolutelyEscapeString( $storage['search']['ageUnder'] );
        $page = absolutelyEscapeString( $storage['search']['page'] );
        $mapWidth = absolutelyEscapeString( $storage['map']['width'] );
        $mapHeight = absolutelyEscapeString( $storage['map']['height'] );
        
        //*********
            //specialization
            if (isset($storage['search']['specialization']))
                $specialization = $storage['search']['specialization'];
            else
                $specialization = array();

            $specialization_ = array();
            foreach ($specialization as $key => $value)
            array_push( $specialization_, absolutelyEscapeString ($value) );

            unset($specialization);        
                $specialization = $specialization_;
            unset ($specialization_);
        //****
            //specialization_INS!!!
            if (isset($storage['search']['specialization_ins']))
                $specialization_ins = $storage['search']['specialization_ins'];
            else
                $specialization_ins = array();

            $specialization_ins_ = array();
            foreach ($specialization_ins as $key => $value)
            array_push( $specialization_ins_, absolutelyEscapeString ($value) );

            unset($specialization_ins);        
                $specialization_ins = $specialization_ins_;
            unset ($specialization_ins_);
            
        //***
        if (isset($storage['search']['arrPodRazdel']))
            $arrPodRazdel = $storage['search']['arrPodRazdel'];
        else
            $arrPodRazdel = array();
       
        $arrPodRazdel_ = array();
        foreach ($arrPodRazdel as $key => $value)
            $arrPodRazdel_[absolutelyEscapeString ($key)] = absolutelyEscapeString ($value);

        unset($arrPodRazdel);        
            $arrPodRazdel = $arrPodRazdel_;
        unset ($arrPodRazdel_);
        
        if (!filter_var($latAround, FILTER_VALIDATE_FLOAT) && $latAround <= 90 && $latAround >= -90)
                $latAround = NULL;
        
        if (!filter_var($lngAround, FILTER_VALIDATE_FLOAT) && $lngAround <= 180 && $lngAround >= -180)
                $lngAround = NULL;
        
        if (!filter_var($zoom, FILTER_VALIDATE_INT) && $zoom <= 15 && $zoom >= 2)
                $zoom = NULL;
        
        if (!filter_var($aim, FILTER_VALIDATE_INT) && $aim <= 1 && $zoom >= 4)
                $aim = NULL;
        
        if (!is_null($latAround) && !is_null($lngAround) && !is_null($zoom) && !is_null($aim)) {

   
        } else {
                $error = 'Ошибка данных. Обратитесь за справкой к администратору';
        }
            
        //вычисление коэффициентов в зависимости от размеров карты
        $k1 = $mapHeight/300;
        $k2 = $mapWidth/120;
        
        if(!$error) {
            
            if ($zoom > 8)
                $radius = (3/8) * pow(2, 15-$zoom);
            else
                $radius = 0;
            
            $difLat = $k1*$radius/117;
            $difLng = $k2*($radius/117)*cos($lngAround*pi()/180);
            
            //*********************************************
            //считаем количество зданий
            
            $queryBuild = "SELECT name, id_building, lat, lng FROM building 
                WHERE ABS (lat-'$latAround') < '$difLat'
                    AND ABS (lng-'$lngAround') < '$difLng'
LIMIT 0, 1000";          
            
            $queryBuild_ = mysql_query ($queryBuild );
            $numBuild = mysql_num_rows($queryBuild_); 
            
            //***
            //считаем фирмы
            $queryFirms = mysql_query("SELECT firms.name, firms.id_firm, building.lat, building.lng FROM firms 
                                            LEFT JOIN building_offices USING (id_office)
                                            LEFT JOIN building USING (id_building)
                                            WHERE ABS (building.lat-'$latAround') < '$difLat'
                                            AND ABS (building.lng-'$lngAround') < '$difLng'
                                            AND not isnull(building.lat)
                                            LIMIT 0, 1000");          
            
            
            $numFirms = mysql_num_rows($queryFirms); 
            
            //считаем свободные офисы
            $queryOffice = mysql_query("SELECT building_offices.id_office, building.lat, building.lng FROM building_offices
                                            LEFT JOIN firms USING (id_office)
                                            LEFT JOIN building USING (id_building)
                                            WHERE ABS (building.lat-'$latAround') < '$difLat'
                                            AND ABS (building.lng-'$lngAround') < '$difLng'
                                            AND not isnull(firms.name)
                                            LIMIT 0, 1000");          

            
            $numOffice = mysql_num_rows($queryOffice); 
            

            $numVacancy = 10;
            $numInsertion = 10;
            
            if ($aim == 1) {

                  $storage['message'] = ''; 
            ob_start();
                include BLOCKS.'_map/yourCity.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'_map/aimSearch.php';
                echo '<BR>';
                include BLOCKS.'_map/fieldsBC.php';
                
                echo '<BR>';
                include BLOCKS.'_map/searchWord.php';
                
                $storage['message']  .= ob_get_contents();    
            ob_end_clean();

         
                        $i = 0;
            $str = '';
         

              
            $select = "SELECT building.name AS name, building.id_building AS id_building, building.lat AS lat, building.lng AS lng FROM building 
            WHERE ABS (lat-'$latAround') < '$difLat'
                      AND ABS (lng-'$lngAround') < '$difLng'";
            
            
            $condition1 = " AND building.id_building
IN (
    SELECT id_building
    FROM building_offices
    WHERE id_office NOT
    IN (
        SELECT id_office
        FROM firms
        )
    )";

           $condition2 = "AND building.id_building
IN (
    SELECT id_building
    FROM building_offices
    WHERE id_office NOT
    IN (
        SELECT id_office
        FROM firms WHERE id_firm
            IN(
                SELECT id_firm FROM vacancy
            )
        )
    )" ;
            
           
            if ($freeOffice == 'true') {
                $queryBuild = $select.$condition1;
                
            } else
                $queryBuild = $select;
            
            if ($freeVacancy == 'true') 
                $queryBuild .= $condition2;
                
            
            
            $query = mysql_query ($queryBuild);
            
            $bcString = '';
            
            $beginList = ($page-1)*10;
            $endList = ($page)*10;
            
            while ($result = mysql_fetch_array ( $query) ){
                
               if (  ($searchWord == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchWord, 'UTF-8' ) ) ) ) { 
                
                   
                   
                $str[$i]['name'] = $result['name'];
                $str[$i]['lat'] = $result['lat'];
                $str[$i]['lng'] = $result['lng'];
                $i++;
                
                $nameBuild = $result['name'];
                
                if ($i <= $endList && $i >= $beginList) {
                    ob_start();
                        include BLOCKS.'_map/bcString.php';
                        $bcString .= ob_get_contents();     
                    ob_end_clean();
                }
                
               }
            }
            

         $storage['message']  .= '<BR>Количество результатов : '.$i.'<BR>';  
         $storage['message']  .= $bcString;  
  
        ob_start();
            include BLOCKS.'_map/pager.php';
            $storage['message'] .= ob_get_contents();     
        ob_end_clean();
            
            
            $storage['map']['markersOut'] = $str;
            
            } //end if  aim == 1 

            
            /*******************************************************/
            //фирмы
             if ($aim == 2) {
                
        
                $storage['message'] = ''; 
                
                //echo $city;
                ob_start();
                include BLOCKS.'_map/yourCity.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'_map/fieldsFirm.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'_map/searchWord.php';
                
                $storage['message']  .= ob_get_contents();    
                ob_end_clean();  

            //*****************
            /*
             * далее идет блок вывода списка фирм
             * 
             */
            //******************
                
            /*
             * получаем список айдишник специализаций для SQL запроса
             */
           $listIdSpec = '999, '; //будет одно значение 999, если ничего не выбрано
           
           foreach($specialization as $key => $value) {
               $listIdSpec .= $value.', ';
           };
            
           $listIdSpec = substr( $listIdSpec, 0, strlen($listIdSpec) - 2 );
            
           $select = "
            SELECT firms.id_firm, firms.name AS name, firms.description AS description, building.lat AS lat, building.lng AS lng
            FROM firms
            
            LEFT JOIN building_offices USING(id_office)
            LEFT JOIN building USING (id_building) 
            
            WHERE firms.id_office IN (
                SELECT building_offices.id_office
                FROM building_offices
                WHERE building_offices.id_building IN (
                    SELECT building.id_building
                    FROM building 
                    WHERE ABS (lat-'$latAround') < '$difLat'
                    AND ABS (lng-'$lngAround') < '$difLng'
                )
            )
           
            AND firms.id_firm IN (
                SELECT id_firm
                FROM firm_specialization
                WHERE id_specialization IN ($listIdSpec)
            )
           ";
           
           //накладываем доп. условия, если нужно искать фирмы со свободными вакансиями
           if ($freeVacancy == 'true') 
           $select .= "AND firms.id_firm IN (
                        SELECT vacancy.id_firm
                        FROM vacancy
                        )
                      ";
            
           $query = mysql_query ($select);
           
           //получаем количество фирм, подходящих критерию
           $numFirms = mysql_num_rows($query);
             
           $vacancyString = '';
            
           $str = '';
           $i = 0;
            
            $beginList = ($page-1)*10;
            $endList = ($page)*10;
            
            while ($result = mysql_fetch_array ( $query) ){
                
               if (  ($searchWord == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchWord, 'UTF-8' ) ) ) ) { 
                   
                    $idFirm = $result['id_firm'];
                    $str[$i]['id']  = $result['id_firm'];
                    $str[$i]['name'] = $result['name'];
                    $str[$i]['lat'] = $result['lat'];
                    $str[$i]['lng'] = $result['lng'];
                    $str[$i]['description'] = $result['description'];
                    $i++;

                    $nameBuild = $result['name'];
                    
                   if ($i <= $endList && $i >= $beginList) {
                        ob_start();
                            include BLOCKS.'_map/vacancyString.php';
                            $vacancyString .= ob_get_contents();     
                        ob_end_clean();
                    }
                
               }
            }
            
             $storage['message'] .= $vacancyString;       
             
              ob_start();
                include BLOCKS.'_map/pager.php';
                $storage['message'] .= ob_get_contents();     
              ob_end_clean();
              
            $storage['map']['markersOut'] = $str;
        }//end if aim == 2
            
            if ($aim == 3) {
                
        
        $salaryFrom =  absolutelyEscapeString( $storage['search']['salaryFrom'] );
        
        if (!filter_var($salaryFrom, FILTER_VALIDATE_INT) || $salaryFrom <= 1) $salaryFrom = 0;
        
        if (!filter_var($experienceFrom, FILTER_VALIDATE_INT) || $experienceFrom <= 1){ $experienceFrom = 0; };
        
        if (!filter_var($ageFrom, FILTER_VALIDATE_INT) || $ageFrom <= 1){ $ageFrom = 0; };
        
        if (!filter_var($ageUnder, FILTER_VALIDATE_INT) || $ageUnder > 50){ $ageUnder = 50; };
        
                
                
                
                $storage['message'] = ''; 
                
                ob_start();
                include BLOCKS.'_map/yourCity.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'_map/aimSearch.php';
                echo '<BR>';
                include BLOCKS.'_map/fieldsVacancy.php';
                
                echo '<BR>';
                include BLOCKS.'_map/searchWord.php';
                
                $storage['message']  .= ob_get_contents();    
                ob_end_clean();  

            
            
            //*************************************************
            $i = 0;
            $str = '';
            
            $listIdSpec = '999, ';
           foreach($specialization as $key => $value) {
               $listIdSpec .= $value.', ';
           };
            
           $listIdSpec = substr($listIdSpec, 0, strlen($listIdSpec) - 2);
            
            $select = "SELECT vacancy.id_vacancy, vacancy.name AS name, building.lat AS lat, building.lng AS lng
            FROM vacancy
            
            LEFT JOIN firms USING(id_firm)
            LEFT JOIN building_offices USING(id_office)
            LEFT JOIN building USING (id_building) 
            
            WHERE vacancy.salary_from > '$salaryFrom'
            AND vacancy.experienceFrom > '$experienceFrom'
            AND vacancy.age_from > '$ageFrom'
            AND vacancy.age_under < '$ageUnder'
            AND vacancy.id_firm IN (
                SELECT firms.id_firm
                FROM firms, firm_specialization
                WHERE firms.id_office IN (
                    SELECT building_offices.id_office
                    FROM building_offices
                    WHERE building_offices.id_building IN (
                        SELECT building.id_building
                        FROM building 
                        WHERE ABS (lat-'$latAround') < '$difLat'
                        AND ABS (lng-'$lngAround') < '$difLng'
                    )
                )
                AND vacancy.id_firm IN (
                    SELECT id_firm
                    FROM firm_specialization
                    WHERE id_specialization IN ($listIdSpec)
                )
            )";
            
            
               
          // echo $select;

             $query = mysql_query ($select);
            
            $vacancyString = '';
            
            $str = '';
            $i = 0;
            
            while ($result = mysql_fetch_array ( $query) ){
                
               if (  ($searchWord == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchWord, 'UTF-8' ) ) ) ) { 
                   
                    $str[$i]['name'] = $result['name'];
                    $str[$i]['lat'] = $result['lat'];
                    $str[$i]['lng'] = $result['lng'];
                    $i++;

                    $nameBuild = $result['name'];

                    ob_start();
                        include BLOCKS.'_map/vacancyString.php';
                        $vacancyString .= ob_get_contents();     
                    ob_end_clean();
                
                
               }
            }
            
             $storage['message'] .= $vacancyString;           
            
            $storage['map']['markersOut'] = $str;
        }//end if aim == 3
        
        if ($aim == 4) {
            
             $salaryFrom =  absolutelyEscapeString( $storage['search']['salaryFrom'] );
        
        if (!filter_var($salaryFrom, FILTER_VALIDATE_INT) || $salaryFrom <= 1) $salaryFrom = 0;
        
        if (!filter_var($experienceFrom, FILTER_VALIDATE_INT) || $experienceFrom <= 1){ $experienceFrom = 0; };
        
        if (!filter_var($ageFrom, FILTER_VALIDATE_INT) || $ageFrom <= 1){ $ageFrom = 0; };
        
        if (!filter_var($ageUnder, FILTER_VALIDATE_INT) || $ageUnder > 50){ $ageUnder = 50; };
        
                
                
                
                $storage['message'] = ''; 
                
                ob_start();
                include BLOCKS.'_map/yourCity.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'_map/aimSearch.php';
                echo '<BR>';
                include BLOCKS.'_map/fieldsInsertion.php';
                
                echo '<BR>';
                include BLOCKS.'_map/searchWord.php';
                
                $storage['message']  .= ob_get_contents();    
                ob_end_clean();  

            
            
            //*************************************************
            $i = 0;
            $str = '';
            
            $listIdSpec = '999, ';
           foreach($specialization_ins as $key => $value) {
               $listIdSpec .= $value.', ';
           };
            
           $listIdSpec = substr($listIdSpec, 0, strlen($listIdSpec) - 2);
            
            $select = "SELECT neftemagnat_bulletin_board.id_bulletin_board, neftemagnat_bulletin_board.name AS name, neftemagnat_bulletin_board.lat AS lat, neftemagnat_bulletin_board.lng AS lng
            FROM neftemagnat_bulletin_board
           
            WHERE ABS (lat-'$latAround') < '$difLat'
                   AND ABS (lng-'$lngAround') < '$difLng'
           AND market_type IN ($listIdSpec)";
            
            
               
          //echo $select;

             $query = mysql_query ($select);
            
            $insertionString = '';
            
            $str = '';
            $i = 0;
            
            while ($result = mysql_fetch_array ( $query) ){
                
               if (  ($searchWord == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchWord, 'UTF-8' ) ) ) ) { 
                   
                    $str[$i]['name'] = $result['name'];
                    $str[$i]['lat'] = $result['lat'];
                    $str[$i]['lng'] = $result['lng'];
                    $i++;

                    $nameInsertion = $result['name'];

                    ob_start();
                        include BLOCKS.'_map/insertionString.php';
                        $insertionString .= ob_get_contents();     
                    ob_end_clean();
                
                
               }
            }
            
             $storage['message'] .= $insertionString;           
            
            $storage['map']['markersOut'] = $str;
            
            
            
            
            
            
        } //end if aim == 4
        
                    $objJSON = new Service_JSON(); // иницилизация объета JSON
                    echo $objJSON->encode($storage); 
            } // end if !error
       
    break; 
    
    case "getCoordCity":
        
        $city = absolutelyEscapeString($dataFromClient['city']);
        
        $cityTranslit = translitIt($city);
        
        $query = mysql_query("SELECT latitude, longitude
                FROM geoip_city
                WHERE city='$cityTranslit'");
        
        
        if ($result = mysql_fetch_array($query) ) {
            
            $answer['lat'] = $result['latitude'];
            $answer['lng'] = $result['longitude'];
            $answer['error'] = FALSE;
        } else {
            $answer['error'] = TRUE;  
        }
        
          $objJSON = new Service_JSON(); // иницилизация
          echo $objJSON->encode($answer);
          
    break;

}